public class Solution {
    public void nextPermutation(int[] nums) {
        int len=nums.length;
        int max=-1;
        int flagi=-1;
        int flagj=-1;
        for(int i=len-1;i>=0;i--){
            if(nums[i]<max){
                flagi=i;
                break;
            }else{
                max=nums[i];
            }
        } if (flagi == -1) {
            ReverseNums(nums, 0);}
        else{
            for(int j=len-1;j>=0;j--){
                if(nums[j]>nums[flagi]){
                    flagj=j;
                    break;
                }
            }
            swap(nums,flagi,flagj);
            ReverseNums(nums,flagi+1);
        }

    }

    private void ReverseNums(int[] nums, int left) {
        int right=nums.length-1;
        while(left<right){
            swap(nums,left,right);
            left++;
            right--;
        }
    }

    public void swap(int[] nums,int i,int j){
        int tmp=nums[i];
        nums[i]=nums[j];
        nums[j]=tmp;
    }



    public int searchInsert(int[] nums, int target) {
        int len=nums.length;
        for(int i=0;i<len;i++){
            if(nums[i]==target){
                return i;
            }else if(nums[i]>target){
                return i-1;
            }
        }
        return len;
    }


    public static void main(String[] args) {
        Solution solution = new Solution();
        solution.nextPermutation(new int[]{1,5,8,4,7,6,5,3,1});
    }
}
